package com.example.zsr.akpautoupdatedemo.download;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.zsr.akpautoupdatedemo.FileUtils.FileInfo;
import com.example.zsr.akpautoupdatedemo.FileUtils.ThreadInfo;
import com.example.zsr.akpautoupdatedemo.db.DBThreadListenerImp;
import com.example.zsr.akpautoupdatedemo.db.DBTreadListener;

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class DownloadTask {
	private Context mContext;
	private FileInfo mFileInfo;
	private DBTreadListener mDbTreadListener;
	private int mFinished = 0;
	public boolean isPause = false;
	public DownloadTask(Context context, FileInfo mFileInfo) {
		this.mContext = context;
		this.mFileInfo = mFileInfo;
		mDbTreadListener = new DBThreadListenerImp(context);
	}
	
	
	public void download(){
		//读取数据库的线程信息
		List<ThreadInfo> threadInfos = mDbTreadListener.getThreads(mFileInfo.getApkurl());
		ThreadInfo threadinfo = null;
		//第一次下载，则本地文件是为空的,我们则来创建一下
		if (threadInfos.size() == 0) {
			threadinfo = new ThreadInfo(0, mFileInfo.getApkurl(), 0, mFileInfo.getLength(), 0);
		}else{
			threadinfo = threadInfos.get(0);
		}
		new DownloadThread(threadinfo).start();
	} 
	
	class DownloadThread extends Thread{
		private ThreadInfo mThreadInfo = null;
		int progress = 0;
		
		public DownloadThread(ThreadInfo mThreadInfo) {
			this.mThreadInfo = mThreadInfo;
		}
		HttpURLConnection con = null;
		RandomAccessFile raf = null;
		InputStream is = null;	
		@Override
		public void run() {
			Log.d("zsr", "isexisits: "+mDbTreadListener.isThreadExsits(mThreadInfo.getUrl(), mThreadInfo.getId()));
			//向数据库插入线程信息
			if(!mDbTreadListener.isThreadExsits(mThreadInfo.getUrl(), mThreadInfo.getId())){
				mDbTreadListener.insertThread(mThreadInfo);
			}
			try {
				URL url = new URL(mThreadInfo.getUrl());
				con = (HttpURLConnection) url.openConnection();
				con.setReadTimeout(3000);
				con.setRequestMethod("GET");
				//设置下载的位置
				int start = mThreadInfo.getStart() + mThreadInfo.getFinished();
				con.setRequestProperty("Range", "bytes="+start+"-"+mThreadInfo.getEnd());
				//设置文件的写入位置
				File file = new File(DownloadService.FILEDIR,mFileInfo.getFileName());
				raf = new RandomAccessFile(file,"rwd");
				raf.seek(start); //seek保证随便下载的位置
				Intent progresslIntent = new Intent("com.msg.apk_install_progress");
				mFinished += mThreadInfo.getFinished(); //重新获取数据库的下载进度
			    //开始下载
				if (con.getResponseCode() == 206) { //因为用到random，所以是接收到部分请求，要用206
					//读取数据
					is = con.getInputStream();
					byte[] buffer = new byte[1024*4];
					int len = -1;
					progresslIntent.putExtra("length", mFileInfo.getLength()); //文件长度
					while((len = is.read(buffer)) != -1){
						//写入文件
						raf.write(buffer,0,len);
						mFinished += len;
						//把进度发送出去
						progress = mFinished*100/mFileInfo.getLength();
						progresslIntent.putExtra("progress", progress);
						progresslIntent.putExtra("mFinished", mFinished);
						mContext.sendBroadcast(progresslIntent);
						//下载暂停时，把进度保存起来
						if (isPause) {
							mDbTreadListener.updateThread(mThreadInfo.getUrl(), mThreadInfo.getId(),
									mFinished);
							return;
						}
						Log.d("zsr","progress: "+progress);
					}
					
					if (progress == 100) {
						Intent installIntent = new Intent("com.msg.apk_installed");
						mContext.sendBroadcast(installIntent);
					}
					//删除线程信息
					mDbTreadListener.deleteThread(mThreadInfo.getUrl(), mThreadInfo.getId());
					
					
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally{
				try {
					con.disconnect();
					raf.close();
					is.close();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			super.run();
		}
	}
	
}
